
import 'dart:developer';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:dio_log/dio_log.dart';
// import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:fluwx/fluwx.dart';
//import 'package:flutter_alipay/flutter_alipay.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/services/location.dart';
import 'package:guochaoapp/services/toast.dart';
import 'package:guochaoapp/config/config.dart';
import 'package:guochaoapp/services/user_service.dart';
import 'package:logging/logging.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';

class GCContainer {

  GCConfig _config;
  GCConfig get config => _config;
  Future<void> onReady;

  static GCContainer _instance;
  static GCContainer get instance => _getInstance();

  factory GCContainer([GCConfig config]) {
    if(_instance == null) {
      _instance = GCContainer._(config);
    }
    return _instance;
  }

  static GCContainer _getInstance() => GCContainer();

  //初始化
  GCContainer._(GCConfig config) {
    _config = config;

    // FlutterBugly.init(
    //   androidAppId: "f3ce644cd5",
    //   iOSAppId: "1f8d2e6567",
    //   // customUpgrade: true,// 调用Android原生升级方式
    // ).then((_result) {
    //   log(_result.toString());
    // });

    registerWxApi(doOnAndroid: true, doOnIOS: true ,appId: config.wechatAppid,universalLink: config.wechatUniversalLink);

    onReady = Future(() async {

      //依赖注入
      //定位服务
      Get.lazyPut<GCLocation>(() => GCLocation());
      Get.lazyPut<GCToast>(() => GCToast());
      Get.put<UserService>(UserService());

      //配置app信息
      _config.packageInfo = await PackageInfo.fromPlatform();
      _config.appDocDir = await getApplicationDocumentsDirectory();

      //日志
      Logger.root.level = _config.loggerLevel;
      Logger.root.onRecord.listen((event) {
        final label = event.loggerName.padRight(3).substring(0, 3).toUpperCase();
        final time = event.time.toIso8601String().substring(0, 23);
        final level = event.level.toString().padRight(4);
        print('$label $time $level ${event.message}');
      });

      //网络请求
      final dio = Dio();
      dio.options.baseUrl = _config.apiBaseUrl;
      dio.options.connectTimeout = 30000;
      dio.options.receiveTimeout = 5000;
      dio.options.responseType = ResponseType.json;
      dio.options.contentType = "application/json";
      dio.interceptors.add(CookieManager(PersistCookieJar(dir: '${_config.appDocDir.path}/cookies')));
      if(_config.debug)
        dio.interceptors.add(DioLogInterceptor());

      HttpClient(_config, dio);
    });
  }

}